package cn.school.demo.ui.my_view

import android.content.Context
import android.graphics.Canvas
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import cn.school.demo.R

/**
 * @Description: Android自定义线
 * @Date 2022-04-28 12:42
 * @Version
 */
class DividerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    View(context, attrs) {
    private val mPaint: Paint
    private var orientation = 0

    fun setBgColor(color: Int) {
        mPaint.color = color
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        if (orientation == ORIENTATION_HORIZONTAL) {
            val center = height * 0.5f
            canvas.drawLine(0f, center, width.toFloat(), center, mPaint)
        } else {
            val center = width * 0.5f
            canvas.drawLine(center, 0f, center, height.toFloat(), mPaint)
        }
    }

    companion object {
        var ORIENTATION_HORIZONTAL = 0
        var ORIENTATION_VERTICAL = 1
    }

    init {
        val dashGap: Int
        val dashLength: Int
        val dashThickness: Int
        val color: Int
        val a = context.theme.obtainStyledAttributes(attrs, R.styleable.DividerView, 0, 0)
        try {
            dashGap = a.getDimensionPixelSize(R.styleable.DividerView_dashGap, 5)
            dashLength = a.getDimensionPixelSize(R.styleable.DividerView_dashLength, 5)
            dashThickness = a.getDimensionPixelSize(R.styleable.DividerView_dashThickness, 3)
            color = a.getColor(R.styleable.DividerView_divider_line_color, -0x000000)
            orientation =
                a.getInt(R.styleable.DividerView_divider_orientation, ORIENTATION_HORIZONTAL)
        } finally {
            a.recycle()
        }
        mPaint = Paint()
        mPaint.apply {
            isAntiAlias = true //抗锯齿
            this.color = color
            strokeWidth = dashThickness.toFloat() //画笔宽度
        }
        /*==============虚线=========*/
        /*mPaint.apply {
            isAntiAlias = true
            this.color = color
            style = Paint.Style.STROKE
            strokeWidth = dashThickness.toFloat()
            pathEffect = DashPathEffect(floatArrayOf(dashGap.toFloat(), dashLength.toFloat()), 0f)
        }*/
    }
}